package com.shyroke.daydayzhuansvc.manager;

import com.shyroke.daydayzhuanapi.constant.CommitConstant;
import com.shyroke.daydayzhuanapi.constant.RedisKeyPrefix;
import com.shyroke.daydayzhuansvc.service.impl.CommitService;
import com.shyroke.daydayzhuansvc.util.CommonUtil;
import com.shyroke.daydayzhuansvc.util.IPUtil;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class ProjectManager {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private CommitService commitService;

    @Async
    public void updateReadAmount(HttpServletRequest request, Integer projectId, String channel) {
        if(CommonUtil.isSpider(request)) {
            logger.info("爬虫访问，忽略不计，{}", request.getHeader("user-agent"));
            return;
        }

        String ip = IPUtil.getIpAddr(request);
        ip = ip.replaceAll(":",".");
        String key = RedisKeyPrefix.PROJECTVIEW+":isViewd:"+projectId+":"+ip;
        Set keys = redisTemplate.keys(key);
        if(CollectionUtils.isEmpty(keys)){
            String viewKey = RedisKeyPrefix.PROJECTVIEW+":isViewd:"+projectId+":"+ip;
            redisTemplate.opsForValue().set(viewKey,null);
            redisTemplate.expire(viewKey,7, TimeUnit.DAYS);
            //说明该IP没有浏览过,在redis里给该文章流量数+1
            this.setCount(projectId, channel);
        }

        //统计今日访问
        String todayKey = RedisKeyPrefix.PROJECTVIEW+":today";
        Object todayCount = redisTemplate.opsForValue().get(todayKey);
        if(todayCount == null) {
            List<String> list = new ArrayList<>();
            list.add(ip);
            redisTemplate.opsForValue().set(todayKey, list);
            redisTemplate.expire(todayKey, 2, TimeUnit.DAYS);
        }else {
            List<String> list = (List<String>) todayCount;
            list.add(ip);
            redisTemplate.opsForValue().set(todayKey, list);
        }
    }

    private void setCount(Integer projectId, String channel) {
        String key = RedisKeyPrefix.PROJECTCOUNT+":viewCount:"+projectId;
        Object countObj = redisTemplate.opsForValue().get(key);

        if(countObj == null){
            redisTemplate.opsForValue().set(key,1);
            redisTemplate.expire(key,7, TimeUnit.DAYS);
        }else{
            int count = (Integer)countObj;
            redisTemplate.opsForValue().set(key,++count);
        }

        if("APP".equals(channel)) {
            String appKey = RedisKeyPrefix.PROJECTCOUNT+":viewCount:app:"+projectId;
            Object appCountObj = redisTemplate.opsForValue().get(appKey);

            if(appCountObj == null) {
                redisTemplate.opsForValue().set(appKey, 1);
                redisTemplate.expire(appKey,7, TimeUnit.DAYS);
            }else {
                int appCount = (Integer)appCountObj;
                redisTemplate.opsForValue().set(appKey, ++appCount);
            }
        }
    }

    @Async
    public void commitSearch(String url) {
        List<String> urlList = new ArrayList<>();
        urlList.add(url);
        try {
            String result = commitService.commitBaidu(CommitConstant.BAIDU_FAST_COMMIT_URL,urlList);
            logger.info("提交百度快速收录结果：{}", result);
        }catch (Exception e) {
            logger.error("提交百度快速收录异常，", e);

            String result3 = commitService.commitBaidu(CommitConstant.BAIDU_COMMIT_URL,urlList);
            logger.info("提交百度快速收录结果：{}", result3);
        }

        String result2 = commitService.commitBing(CommitConstant.BING_COMMIT_URL,urlList);
        logger.info("提交bing收录结果：{}", result2);
    }
}
